//
//  GZPersonInfoViewController.swift
//  GZMarathon
//
//  Created by apple on 2021/11/10.
//

import UIKit
import SVProgressHUD
class GZPersonInfoViewController: UIViewController
{

    @IBOutlet weak var tab: UITableView!
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "个人信息"
        tab.removeMoreLine()
        // Do any additional setup after loading the view.
    }

    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        tab.reloadData()
    }


}

extension GZPersonInfoViewController:UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 54
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "PersonTableViewCell", for: indexPath) as! PersonTableViewCell
        switch indexPath.row {
        case 0:
            cell.icon.isHidden = false
            cell.subLabel.isHidden = true
            cell.title.text = "头像"
            updateAvatar(imgView: cell.icon)
        case 1:
            cell.icon.isHidden = true
            cell.subLabel.isHidden = false
            cell.subLabel.text = GZCurrentUser.shared.currentUser?.account_name
            cell.title.text = "用户名称"
        default:
            cell.icon.isHidden = true
            cell.subLabel.isHidden = true
            cell.title.text = "修改密码"
        }
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        switch indexPath.row {
        case 0:
            print("1")
            showBottomAlert()
        case 1:
            let vc = UIStoryboard(name: "GM", bundle: nil).instantiateViewController(withIdentifier: "SettingViewController") as! SettingViewController
            
            
            self.navigationController?.pushViewController(vc, animated: true)
            
            print("2")
        default:
            let vc = UIStoryboard(name: "GM", bundle: nil).instantiateViewController(withIdentifier: "FixPDViewController") as! FixPDViewController
            self.navigationController?.pushViewController(vc, animated: true)
            
            print("3")
        }
    }
    
    func showBottomAlert(){

            let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
            
            let cancel = UIAlertAction(title:NSLocalizedString("取消", comment: ""), style: .cancel, handler: nil)
            let takingPictures = UIAlertAction(title:NSLocalizedString("拍照", comment: ""), style: .default){ action in
                self.goCamera()
                
            }
            let localPhoto = UIAlertAction(title:NSLocalizedString("相册", comment: ""), style: .default){ action in
                self.goImage()
                
            }
            
            alertController.addAction(cancel)
            alertController.addAction(takingPictures)
            alertController.addAction(localPhoto)
            self.modalPresentationStyle = .fullScreen
            self.present(alertController, animated:true, completion:nil)
        }
        
        
    func goCamera(){
            if UIImagePickerController.isSourceTypeAvailable(.camera){
                let  cameraPicker = UIImagePickerController()
                cameraPicker.delegate = self
                cameraPicker.allowsEditing = true
                cameraPicker.sourceType = .camera
                //在需要的地方present出来
                
                self.present(cameraPicker, animated: true, completion: nil)
            } else {
                print("不支持拍照")
            }
            
        }
    func goImage(){
        let photoPicker =  UIImagePickerController()
        photoPicker.delegate = self
        photoPicker.allowsEditing = true
        photoPicker.sourceType = .photoLibrary
        //在需要的地方present出来
        self.present(photoPicker, animated: true, completion: nil)
//        self.get.present(photoPicker, animated: true, completion: nil)
        
    }
    
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info:[UIImagePickerController.InfoKey : Any]) {
        
        let image : UIImage = info[UIImagePickerController.InfoKey.editedImage] as! UIImage
               //显示设置的照片
        uploadImg(img: image)
        self.dismiss(animated: true, completion: nil)
    }
    
    func uploadImg(img: UIImage) {
        
        SVProgressHUD.show()
        
        ApiLoadingProvider.request(EBAPI.uploadAvatar(img: img), model: GZAvatarModel.self) { model, isSuccess in
            SVProgressHUD.dismiss()
            
            guard let avatar = model?.account_avatar else{
                SVProgressHUD.showError(withStatus: "修改失败, 请稍后再试")
                return
            }
            
            if avatar.count == 0{
                SVProgressHUD.showError(withStatus: "修改失败, 请稍后再试")
                return
            }else{
                SVProgressHUD.showSuccess(withStatus: "修改成功")
                GZCurrentUser.shared.currentUser?.account_avatar = avatar
                self.tab.reloadData()
            }

        }
        
    }
    
    
    func updateAvatar(imgView: UIImageView){
        guard let urlStr = GZCurrentUser.shared.currentUser?.account_avatar else{
            return
        }
        
        guard let url = URL(string: urlStr) else {
            return
        }
        imgView.kf.setImage(with: url)
    }

    
}
